<template>
  <scroll-view enable-back-to-top scroll-y>

    <!-- 错题统计 -->
    <view class="error-over">
      <view class="error-over-header">
        <view class="error-over-header-title">错题统计</view>
        <view class="error-over-header-del-btn icon-delete" @tap="openClearErrorQuestionModal">清空</view>
      </view>
      <view>
        <view class="error-over-box">
          <view class="error-over-info-titles">
            <view class="title-item"
              @tap="toExercise(ExerciseTypeEnum.SequenceExerciseErrorQuestions, errorQuestionOver.allErrorQuestionCount)">
              <view class="title-num">{{ errorQuestionOver.allErrorQuestionCount }} <text
                  class="title-num-icon icon-right"></text></view>
              <view class="title-txt">全部错题</view>
            </view>

            <view class="title-item"
              @tap="toExercise(ExerciseTypeEnum.TodayErrorQuestionExercise, errorQuestionOver.todayErrorQuestionCount)">
              <view class="title-num">{{ errorQuestionOver.todayErrorQuestionCount }} <text
                  class="title-num-icon icon-right"></text></view>
              <view class="title-txt">
                今日错题</view>
            </view>
            <view class=" title-item">
              <view class="title-num error">{{ errorQuestionOver.correctRate }}<text class="rate">%</text>
              </view>
              <view class="title-txt">错题/已做题</view>
            </view>
          </view>

          <!-- 预测考试通过率 -->
          <view class="forecast-exam-pass-rate">
            <view class="exam-pass-rate-tips">
              <text class="tips-label">预测考试通过率<text class="tips-label-keyword">很低</text></text>
              <text class="tips-desc">定制课程高效学</text>
            </view>
            <view class="exam-pass-rate-button">去提升</view>
          </view>
          <!-- 自动易错错题 -->
          <view class="auto-remove-error">
            <view class="left">答对自动移出错题</view>
            <view class="right">
              <view class="tips" v-if="isAutoRemoveError">连续答对<text class='num'>{{
                autoRemoveErrorAnswerCorrectNum
                  }}次</text>后
              </view>
              <uv-picker ref="autoRemoveErrorPickerRef" :columns="autoRemoveErrorColumns"
                :title="autoRemoveErrorPickerRefTitle" round="10" itemHeight="32" confirmText="完成" cancelColor="#4c4c4c"
                confirmColor="#4c4c4c" @confirm="autoRemoveErrorNumConfirm" @close="autoRemoveErrorNumClose"
                @change="autoRemoveErrorNumChange"></uv-picker>
              <switch ref="autoRemoveErrorSwitchRef" class="switch" :checked="isAutoRemoveError" color="#27c463"
                @change="autoRemoveErrorSwitchChange" />
            </view>
          </view>
        </view>
      </view>

    </view>
    <view class="easy-error-box">
      <view class="easy-error">
        <view class="easy-error-left">
          <image class="easy-error-img" :src="useEcRecordsEasyErrorImg()" mode="scaleToFill" />
          <view class="easy-error-txt">高频易错题，提分必做</view>
        </view>
        <view class="easy-error-right">
          <view class="btn" @tap="toExercise(ExerciseTypeEnum.SpecialExerciseEasyErrorQuestions)">马上去做</view>
        </view>
      </view>
    </view>
    <!-- 错题详情 -->
    <view class="error-details">
      <view class="details-title">
        <view class="left">
          <text class="title-name">错题详情</text>
          <text class="title-tips icon-shuaxin">同步错题</text>
        </view>
        <view class="right">
          <view class="group-name" @tap="isErrorGroupSelectListShow = !isErrorGroupSelectListShow">
            {{ acitveErrorGroupName }}
            <text class='group-select-icon icon-down'></text>
          </view>
          <view class="select-group-name-list" :class="{ 'show': isErrorGroupSelectListShow }">
            <view class="select-option" v-for="(item, index) in errorGroupList" :key="index"
              @tap="onErrorGroupSelected(item.index)">
              {{ item.label }}
            </view>
          </view>
        </view>
      </view>
      <!-- 数据列表 -->
      <view class="details-list">
        <view class="list-item" v-for="(item, index) in questionGroupList" :key="index"
          @tap="toExercise(acitveErrorGroupIndex, item.count, item.code)">
          <view class="list-item-lable">
            <text class="index">{{ index + 1 }}</text>
            {{ item.name }}
          </view>
          <view class="list-item-num">
            {{ item.count }}题<text class="list-item-num-icon icon-right"></text>
          </view>
        </view>
      </view>
    </view>

  </scroll-view>
  <uv-modal ref="clearErrorQuestionModal" title="温馨提示" content='你确定清空所有错题吗' confirmText="确定" :showConfirmButton="true"
    :showCancelButton="true" confirmColor="#606266" align="center" width="500rpx"
    @confirm="confirmClearErrorQuestion"></uv-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, computed } from 'vue'
  import { ExerciseTypeEnum } from '@/api/constants'
  import { useEcRecordsEasyErrorImg } from '@/pagesExercise/static/images'

  import { useSettingStore } from '@/stores/modules/setting'
  import { useExericseStore } from '@/stores/modules/exercise_store'
  import { useLearnBaseInfoStore } from '@/stores/modules/learn_base_info'

  import { useClearErrorQuestion, useErrorQuestionOver } from '@/composables/Exercise'


  // 相关配置
  const settingStore = useSettingStore()
  const exericseStore = useExericseStore()
  const learnBaseInfoStore = useLearnBaseInfoStore()

  const props = defineProps<{
    baseType: string
  }>()

  // 题库类型
  const baseType = computed(() => props.baseType)
  //清空错题确认对话框
  const clearErrorQuestionModal = ref()
  // 错题统计
  const errorQuestionOver = computed(() => useErrorQuestionOver(baseType.value))
  // 自动移除错题Picker
  const autoRemoveErrorPickerRef = ref()
  // 自动移除Switch
  const autoRemoveErrorSwitchRef = ref<UniHelper.SwitchInstance>()
  // 字段移除错题次数
  const autoRemoveErrorColumns = reactive<string[][]>([[
    '1', '2', '3', '4', '5', '6', '7', '8', '9',
  ]])
  // 是否自动移除错题
  const isAutoRemoveError = computed(() => settingStore.autoRemoveErrorQuestion.autoRemove)
  // 自动易错错题的答对次数
  const autoRemoveErrorAnswerCorrectNum = computed(() => settingStore.autoRemoveErrorQuestion.answerCorrectNum)
  // 自动移除错题次数
  const activeAutoRemoveErrorNum = ref<number>(autoRemoveErrorAnswerCorrectNum.value)
  //
  const autoRemoveErrorPickerRefTitle = computed(() => {
    return `连续答对${activeAutoRemoveErrorNum.value}次后自动移出错题`
  })
  // 错题展示数据列表
  const errorGroupList = reactive([
    {
      index: ExerciseTypeEnum.AnswerErrorNumExercise,
      label: '按答错次数展示'
    },
    {
      index: ExerciseTypeEnum.ChapterErrorQuestionExercise,
      label: '按章节展示'
    },
    {
      index: ExerciseTypeEnum.KnowErrorQuestionExercise,
      label: '按知识点展示'
    }
  ])

  // 选择的展示方式索引
  const acitveErrorGroupIndex = computed(() => settingStore.errorQuestionGroupIndex)

  // 选择的展示方式
  const acitveErrorGroupName = computed(() => {
    return errorGroupList.find(item => item.index == acitveErrorGroupIndex.value)?.label?.replace('展示', '')
  })

  // 错题分组列表是否展示
  const isErrorGroupSelectListShow = ref<boolean>(false)
  /**
   * 打开清空错题对话框
   */
  const openClearErrorQuestionModal = () => {
    console.log('baseType', baseType)
    if (errorQuestionOver.value.allErrorQuestionCount == 0) {
      uni.showToast({
        title: '您还没有错题哦，先去做题吧~',
        icon: 'none',
        duration: 2000
      })
      return
    }
    clearErrorQuestionModal.value.open()
  }

  // 确认清空错题
  const confirmClearErrorQuestion = () => {
    useClearErrorQuestion(baseType.value)
  }
  //自动移除错题选择
  const autoRemoveErrorSwitchChange = (e: any) => {
    let autoRemoveErrorSwitchChangeVal = e.detail.value
    settingStore.setAutoRemoveErrorQuestion(autoRemoveErrorSwitchChangeVal)
    if (autoRemoveErrorSwitchChangeVal) {
      autoRemoveErrorPickerRef.value?.setIndexs([activeAutoRemoveErrorNum.value - 1], true)
      autoRemoveErrorPickerRef.value?.open()
    }
  }

  //自动移除错题次数发生改变
  const autoRemoveErrorNumChange = (e: any) => {
    activeAutoRemoveErrorNum.value = e.value[0]
  }
  //自动移除错题次数确认
  const autoRemoveErrorNumConfirm = (e: any) => {
    activeAutoRemoveErrorNum.value = e.value[0]
    settingStore.setAutoRemoveErrorQuestionAnswerCorrectNum(activeAutoRemoveErrorNum.value)
  }
  // 自动移除错题Picker关闭
  const autoRemoveErrorNumClose = () => {
    activeAutoRemoveErrorNum.value = autoRemoveErrorAnswerCorrectNum.value
  }

  //错误列表选择事件
  const onErrorGroupSelected = (index: ExerciseTypeEnum) => {
    settingStore.setErrorQuestionGroupIndex(index)
    isErrorGroupSelectListShow.value = false
  }

  //试题分组对象
  interface QuestionGroup {
    name: string,
    code: number,
    count: number
  }
  // 试题分组展示列表
  const questionGroupList = computed(() => {
    let dataList: QuestionGroup[] = []
    switch (acitveErrorGroupIndex.value) {
      case ExerciseTypeEnum.AnswerErrorNumExercise:
        dataList = getQuestionGroupListByAnswerErrorNum()
        break
      case ExerciseTypeEnum.ChapterErrorQuestionExercise:
        dataList = getQuestionGroupListByChapter()
        break
      case ExerciseTypeEnum.KnowErrorQuestionExercise:
        dataList = getQuestionGroupListByKnow()
        break
      default:
        dataList = getQuestionGroupListByAnswerErrorNum()
        break
    }
    return dataList
  })

  // 答错次数列表
  const answerErrorNumList: QuestionGroup[] = [
    {
      name: '答错5次及以上',
      code: 5,
      count: 0,
    },
    {
      name: '答错4次',
      code: 4,
      count: 0,
    },
    {
      name: '答错3次',
      code: 3,
      count: 0,
    },
    {
      name: '答错2次',
      code: 2,
      count: 0,
    },
    {
      name: '答错1次',
      code: 1,
      count: 0,
    },
  ]
  // 根据答错次数获取试题分组
  const getQuestionGroupListByAnswerErrorNum = () => {

    let answerErrorQuestions = exericseStore.questionAnswerErrors.filter(item => item.baseTypeCode == baseType.value)

    answerErrorNumList.forEach(answerErrorNum => {
      if (answerErrorNum.count === 5) {
        answerErrorNum.count = answerErrorQuestions.filter(item => item.errorCount >= answerErrorNum.code).length
      }
      else {
        answerErrorNum.count = answerErrorQuestions.filter(item => item.errorCount == answerErrorNum.code).length
      }
    })

    return answerErrorNumList
  }

  // 根据章节试题分组
  const getQuestionGroupListByChapter = () => {
    let answerErrorQuestions = exericseStore.questionAnswerErrors.filter(item => item.baseTypeCode == baseType.value).map(item => item.questionId)
    let chapterList = learnBaseInfoStore.learnBaseInfo.classes?.filter(item => item.baseType == baseType.value)
    let questionList = learnBaseInfoStore.questions(baseType.value).filter((question: any) => answerErrorQuestions.includes(question.questionId))
    let chapterQuestionGroupList = chapterList?.map((chapter) => {
      let questionGroup: QuestionGroup = { name: chapter.name!, code: Number.parseInt(chapter.code!), count: 0 }
      questionGroup.count = questionList.filter((question: any) => question.classesCode == chapter.code).length
      return questionGroup
    })
    return chapterQuestionGroupList!
  }

  // 根据考点试题分组
  const getQuestionGroupListByKnow = () => {
    // 得到错题
    let answerErrorQuestions = exericseStore.questionAnswerErrors.filter(item => item.baseTypeCode === baseType.value).map(item => item.questionId)
    // 得到考点
    let knowList = exericseStore.knowsExerciseProgress.filter(know => know.baseTypeCode === baseType.value).filter(know => {
      let errorQuestions = know.questions?.some(questionId => answerErrorQuestions.includes(questionId))
      return errorQuestions
    })

    let knowQuestionGroupList = knowList?.map((know) => {
      let questionGroup: QuestionGroup = { name: know.name!, code: know.id!, count: 0 }
      let knowErrorQuestionCount = know.questions?.filter(questionId => answerErrorQuestions.includes(questionId)).length
      if (knowErrorQuestionCount && knowErrorQuestionCount >= 1) {
        questionGroup.count = knowErrorQuestionCount
      }
      return questionGroup
    })
    return knowQuestionGroupList.filter(item => item.count >= 1)
  }

  // 去练习
  const toExercise = (exerciseType: ExerciseTypeEnum, questionCount?: number, code?: string | number) => {
    if (questionCount === 0) {
      return
    }

    uni.navigateTo({
      url: `/pagesExercise/answer/answer?exerciseType=${exerciseType}&baseType=${baseType.value}&code=${code}`
    })

  }
</script>

<style lang="scss" scoped>
  .viewport {
    display: flex;
    flex-direction: column;

  }

  .error-over {
    margin-top: 1rpx;
    padding: 0 30rpx;

    .error-over-header {
      display: flex;
      justify-content: space-between;

      .error-over-header-title {
        font-size: 40rpx;
        font-weight: bold;
        color: #323131;


      }

      .error-over-header-del-btn {
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 28rpx;
        color: #2f2e2d;

        &::before {
          margin-right: 10px;
        }
      }

    }

    .error-over-box {
      margin-top: 26rpx;
      padding: 30rpx 15rpx;
      background-color: #fff;

      .error-over-info-titles {
        display: flex;
        justify-content: space-around;

        .title-item {
          display: flex;
          flex-direction: column;
          align-items: center;

          .title-num {
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 46rpx;
            font-weight: bold;
            color: #333333;

            .title-num-icon {
              margin-left: 5rpx;

              font-size: 20rpx;
            }

            &.error {
              color: #ff595b;
              align-items: flex-end;

              .rate {
                margin-bottom: 4rpx;
                font-size: 30rpx;
                font-weight: normal;
              }
            }

          }

          .title-txt {
            font-size: 26rpx;
            color: #898989;
          }
        }
      }

      // 预测考试通过率
      .forecast-exam-pass-rate {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 32rpx;
        padding: 20rpx;
        font-size: 26rpx;
        background-color: #fff9ee;
        border-radius: 20rpx;
        border: solid 2rpx #ffe0ad;
        font-size: 26rpx;
        color: #141818;

        .exam-pass-rate-tips {
          display: flex;
          flex-direction: column;

          .tips-label {
            .tips-label-keyword {
              padding-left: 10rpx;
              font-size: 27rpx;
              color: #fa6062;
            }
          }

          .tips-desc {
            margin-top: 10rpx;
            font-size: 22rpx;
          }
        }

        .exam-pass-rate-button {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 140rpx;
          height: 50rpx;
          font-size: 24rpx;
          color: #441d00;
          background-image: linear-gradient(-90deg,
              #fac15e 0%,
              #fac96f 26%,
              #fad07f 51%,
              #fcde95 100%),
            linear-gradient(#58beff,
              #58beff);
          border-radius: 25rpx;
        }

      }

      // 自动易错错题
      .auto-remove-error {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 20rpx;

        .left {
          font-size: 30rpx;
          font-weight: bold;
          color: #393939;

        }

        .right {
          display: flex;
          align-items: center;

          .tips {
            margin-right: 10rpx;
            font-size: 26rpx;
            color: #393939;

            .num {
              color: #ff4a4d;
            }
          }
        }
      }
    }
  }


  // 易错题
  .easy-error-box {
    margin: 20rpx 27rpx 0;
    height: 106rpx;
    background-image: linear-gradient(0deg,
        #d4e4ff 0%,
        #dde7ff 0%,
        #e5eafe 0%,
        #adc4f9 0%,
        #749df3 0%,
        #aac3f8 0%,
        #e0e8fc 0%,
        #eeada2 0%,
        #fb7147 0%,
        #f14c89 100%);
    border-radius: 18rpx;

    .easy-error {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 20rpx;
      width: 100%;
      margin-left: 10rpx;
      height: 106rpx;
      background-color: #fff;
      border-radius: 10rpx;

      .easy-error-left {
        display: flex;

        .easy-error-img {
          width: 116rpx;
          height: 36rpx;
        }

        .easy-error-txt {
          margin-left: 25rpx;
          font-size: 24rpx;
          color: #838383;
        }
      }

      .easy-error-right {
        .btn {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 148rpx;
          height: 55rpx;
          font-size: 24rpx;
          color: #fff;
          background-image: linear-gradient(-89deg,
              #d4e4ff 0%,
              #dde7ff 0%,
              #e5eafe 0%,
              #adc4f9 0%,
              #749df3 0%,
              #aac3f8 0%,
              #e0e8fc 0%,
              #eeada2 0%,
              #fb7147 0%,
              #f14c89 100%),
            linear-gradient(#f4f9ff,
              #f4f9ff);
          background-blend-mode: normal,
            normal;
          border-radius: 28rpx;
        }
      }

    }
  }

  // 易错详情
  .error-details {
    display: flex;
    flex-direction: column;
    flex: 1; // 易错题

    margin-top: 40rpx;
    padding: 30rpx 40rpx;

    background-color: #fff;

    // 详情标题
    .details-title {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .left {
        display: flex;
        align-items: end;

        .title-name {
          font-size: 36rpx;
          font-weight: bold;
          color: #323131;

        }

        .title-tips {
          font-size: 22rpx;
          color: #868686;
          margin-left: 10rpx;

        }
      }

      .right {
        position: relative;

        .group-name {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 200rpx;
          height: 60rpx;
          font-size: 24rpx;
          color: #323131;
          background-color: #f7f7f7;
          border-radius: 28rpx;

          .group-select-icon {
            margin-top: 5rpx;
            margin-left: 8rpx;
            font-size: 22rpx;
          }
        }

        .select-group-name-list {
          position: absolute;
          z-index: 1000;
          top: 68rpx; // 51 +
          right: 0;
          display: flex;
          flex-direction: column;
          align-items: center;
          width: 280rpx;
          height: 0rpx;
          background-color: #FFFFFF;
          box-shadow: 0 2px 12px rgba(0, 0, 0, .1);
          transition: height .2s;
          overflow: hidden;

          &.show {
            height: 300rpx;
          }

          .select-option {
            margin: 40rpx 0 10rpx;
            font-size: 28rpx;
            color: #323232;
          }
        }
      }
    }

    // 详情列表
    .details-list {
      margin-top: 40rpx;

      .list-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        height: 80rpx;
        font-size: 28rpx;
        color: #323131;

        .list-item-lable {
          display: flex;
          align-items: center;

          .index {
            display: flex;
            justify-content: center;
            margin-right: 20rpx;
            width: 33rpx;
            height: 33rpx;
            font-size: 22rpx;
            color: #fff;
            background-color: #ff6e2d;
            box-shadow: -2rpx -2rpx 7rpx 0rpx rgba(252, 89, 17, 0.24);
            border-radius: 50%;
          }
        }

        .list-item-num {
          display: flex;
          align-items: center;
          font-size: 26rpx;
          color: #959595;

          .list-item-num-icon {
            margin-left: 10rpx;
            font-size: 20rpx;
          }
        }
      }
    }

  }



</style>
